package com.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.apache.http.HttpStatus;

import android.os.Handler;
import android.os.Message;

import com.android.ocean.util.net.ResEntity;

public class UFileUtil {
	/**
	 * 上传文件到php服务器， httpURLConnection.setRequestProperty表示设置头信息
	 * dos.write会写到body里面
	 * 
	 * 注意：body里的BOUNDARY比header里多“--” 有多个文件，需要写入分割dos.write("\r\n".getBytes());
	 * 
	 * 
	 * 
	 * 
	 * 
	 */

	private static final int DEFAULT_BUFF_SIZE = 8192;
	private static final int READ_TIMEOUT = 15000;
	private static final int CONNECTION_TIMEOUT = 15000;
	private static final String T_JPG = "jpg";
	private static final String T_PNG = "png";
	private static final String T_AMR = "amr";
	private static final String T_MP4 = "mp4";
	private static final String T_3GP = "3gp";
	

	public static ResEntity uploadFile(String serverUrl, String filePath,
			String fileName) throws MalformedURLException, ProtocolException,
			FileNotFoundException, IOException {
		ResEntity ressult = new ResEntity();
		String BOUNDARY = "---------------------------"
				+ String.valueOf(System.currentTimeMillis());// 各个参数的间隔符，可自定义，但不能与发送内容有重复部分

		String srcPath = filePath + fileName;
		URL url = new URL(serverUrl);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		// 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
		// 允许输入输出流
		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setUseCaches(false);
		// 超时时间设置
		httpURLConnection.setReadTimeout(READ_TIMEOUT);
		httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
		// 使用POST方法
		httpURLConnection.setRequestMethod("POST");
		// 设置header
		httpURLConnection.setRequestProperty("Connection", "Keep-alive");
		httpURLConnection
				.setRequestProperty("Accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpURLConnection
				.setRequestProperty("Accept-Encoding", "gzip, deflate");
		httpURLConnection.setRequestProperty("Accept-Language",
				"en-US,en;q=0.5");
		httpURLConnection.setRequestProperty("Cookie",
				"PHPSESSID=e11u15nssoc3l8g69smajo2uu0");
		httpURLConnection
				.setRequestProperty(
						"User-Agent",
						"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0");

		httpURLConnection.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + BOUNDARY);
		httpURLConnection.setRequestProperty("Referer",
				"http://i-artist.demo.wilead.com/upload");
		StringBuilder beforeSb = new StringBuilder();
		beforeSb.append("--" + BOUNDARY + "\r\n");
		beforeSb.append("Content-Disposition: form-data; name=\"form[file]\"; filename=\""
				+ fileName + "\"" + "\r\n");
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		
		if (fileType.equalsIgnoreCase(T_PNG)) {
			beforeSb.append("Content-Type：image/png");
			httpURLConnection.setRequestProperty("ContentType", "image/png");
		} else if (fileType.equalsIgnoreCase(T_JPG)) {
			beforeSb.append("Content-Type：image/jpeg");
			httpURLConnection.setRequestProperty("ContentType", "image/jpeg");
		} else if (fileType.equalsIgnoreCase(T_AMR)) {
			beforeSb.append("Content-Type: application/octet-stream");
			httpURLConnection.setRequestProperty("ContentType",
					"application/octet-stream");
		} else if (fileType.equalsIgnoreCase(T_MP4)) {
			beforeSb.append("Content-Type: video/mp4");
			httpURLConnection.setRequestProperty("ContentType", "video/mp4");
		}else if (fileType.equalsIgnoreCase(T_3GP)) {
			beforeSb.append("Content-Type: video/3gp");
			httpURLConnection.setRequestProperty("ContentType", "video/3gp");
		}
		beforeSb.append("\r\n" + "\r\n");
		// 二进制

		StringBuilder afterSb = new StringBuilder();
		afterSb.append("--" + BOUNDARY + "\r\n" + "\r\n");
		afterSb.append("Content-Disposition: form-data; name=\"form[_token]\"\r\n\r\n");
		afterSb.append("241ba86ae544e2247cfd9fea8a6db674f06627a7" + "\r\n");
		afterSb.append("--" + BOUNDARY + "--\r\n" + "\r\n");
		File f = new File(srcPath);

		long content_len = beforeSb.toString().getBytes().length
				+ afterSb.toString().getBytes().length + f.length()
				+ "\r\n".getBytes().length;
		httpURLConnection
				.setRequestProperty("Content-Length", content_len + "");

		DataOutputStream dos = new DataOutputStream(
				httpURLConnection.getOutputStream());
		/********** 此处写入body **************************************/

		// 写入头
		dos.write(beforeSb.toString().getBytes("UTF-8"));
		// 写入文件start
		FileInputStream fis = null;
		fis = new FileInputStream(srcPath);

		byte[] buffer = new byte[1024 * 8];
		int len = -1;
		while ((len = fis.read(buffer)) != -1) {
			System.out.println("---------------len:" + len);
			dos.write(buffer, 0, len);
		}
		// 写入文件end
		// 多个写入分割
		dos.write("\r\n".getBytes("UTF-8"));
		// 写入end
		dos.write(afterSb.toString().getBytes("UTF-8"));
		fis.close();
		dos.flush();

		ressult.code = httpURLConnection.getResponseCode();
		if (httpURLConnection.getResponseCode() == HttpStatus.SC_OK) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpURLConnection.getInputStream()), 8192);// 8k
			StringBuilder sb = new StringBuilder();
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {

					sb.append(line + "\n");
				}
				ressult.jsonStr = sb.toString().trim();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		if (httpURLConnection != null) {
			httpURLConnection.disconnect();
		}
		return ressult;
	}

	/**************** 加进度条需加一下代码 *****************************************************************************************/

	private static final int DO_SIZE = 1;
	private static final int DO_ING = 2;
	private static final int DO_ERR = 3;
	private static final int DO_COMPLETE = 4;
	private static final int DO_CANCEL = 5;
	private static final int KB = 1024;
	boolean canceled = false;
	long totalSize = 0;
	long currentSize = 0;
	UpCallback doCb;
	private String serverUrl;
	private String filePath;
	private String fileName;

	public UFileUtil(UpCallback doCb, String serverUrl, String filePath,
			String fileName) {
		super();
		this.doCb = doCb;
		this.serverUrl = serverUrl;
		this.filePath = filePath;
		this.fileName = fileName;
	}

	public void upload() {
		new Thread(runable).start();
	}

	public UFileUtil() {
		super();
	}

	public void cancelDownload() {
		canceled = true;
	}

	Handler updateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case DO_SIZE:

				doCb.doSize(totalSize/KB);
				break;
			case DO_ING:

				doCb.doIng(currentSize/KB-5);
				break;
			case DO_ERR:

				doCb.doError((String) msg.obj);
				break;
			case DO_COMPLETE:

				doCb.doCompleted((String) msg.obj);
				break;
			case DO_CANCEL:

				doCb.doCanceled();
			default:
				break;
			}
		}
	};

	Runnable runable = new Runnable() {

		@Override
		public void run() {
			uploadFileProgress(serverUrl, filePath, fileName);
		}
	};

	public void uploadFileProgress(String serverUrl, String filePath,
			String fileName) {
		String result = "";
		FileInputStream fis = null;
		HttpURLConnection httpURLConnection = null;
		DataOutputStream dos = null;
		try {
			String BOUNDARY = "---------------------------"
					+ String.valueOf(System.currentTimeMillis());// 各个参数的间隔符，可自定义，但不能与发送内容有重复部分

			String srcPath = filePath + fileName;
			URL url = new URL(serverUrl);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			// 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
			// 允许输入输出流
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			// 超时时间设置
			httpURLConnection.setReadTimeout(READ_TIMEOUT);
			httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
			// 使用POST方法
			httpURLConnection.setRequestMethod("POST");
			// 设置header
			httpURLConnection.setRequestProperty("Connection", "Keep-alive");
			httpURLConnection
					.setRequestProperty("Accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			httpURLConnection.setRequestProperty("Accept-Encoding",
					"gzip, deflate");
			httpURLConnection.setRequestProperty("Accept-Language",
					"en-US,en;q=0.5");
			httpURLConnection.setRequestProperty("Cookie",
					"PHPSESSID=e11u15nssoc3l8g69smajo2uu0");
			
			httpURLConnection
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0");

			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			httpURLConnection.setRequestProperty("Referer",
					"http://i-artist.demo.wilead.com/upload");
			StringBuilder beforeSb = new StringBuilder();
			beforeSb.append("--" + BOUNDARY + "\r\n");
			beforeSb.append("Content-Disposition: form-data; name=\"form[file]\"; filename=\""
					+ fileName + "\"" + "\r\n");
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
			if (fileType.equalsIgnoreCase(T_PNG)) {
				beforeSb.append("Content-Type：image/png");
				httpURLConnection
						.setRequestProperty("ContentType", "image/png");
			} else if (fileType.equalsIgnoreCase(T_JPG)) {
				beforeSb.append("Content-Type：image/jpeg");
				httpURLConnection.setRequestProperty("ContentType",
						"image/jpeg");
			} else if (fileType.equalsIgnoreCase(T_AMR)) {
				beforeSb.append("Content-Type: application/octet-stream");
				httpURLConnection.setRequestProperty("ContentType",
						"application/octet-stream");
			} else if (fileType.equalsIgnoreCase(T_MP4)) {
				beforeSb.append("Content-Type: video/mp4");
				httpURLConnection
						.setRequestProperty("ContentType", "video/mp4");
			}
			beforeSb.append("\r\n" + "\r\n");
			// 二进制

			StringBuilder afterSb = new StringBuilder();
			afterSb.append("--" + BOUNDARY + "\r\n" + "\r\n");
			afterSb.append("Content-Disposition: form-data; name=\"form[_token]\"\r\n\r\n");
			afterSb.append("241ba86ae544e2247cfd9fea8a6db674f06627a7" + "\r\n");
			afterSb.append("--" + BOUNDARY + "--\r\n" + "\r\n");
			File f = new File(srcPath);
			totalSize = f.length();
			updateHandler.sendMessage(updateHandler.obtainMessage(DO_SIZE));

			long content_len = beforeSb.toString().getBytes().length
					+ afterSb.toString().getBytes().length + f.length()
					+ "\r\n".getBytes().length;
			httpURLConnection.setRequestProperty("Content-Length", content_len
					+ "");
			httpURLConnection.setFixedLengthStreamingMode((int)content_len);
			dos = new DataOutputStream(httpURLConnection.getOutputStream());
			
			/********** 此处写入body **************************************/

			// 写入头
			dos.write(beforeSb.toString().getBytes("UTF-8"));

			fis = new FileInputStream(srcPath);

			byte[] buffer = new byte[1024 * 8];
			int len = -1;
			while ((!canceled) && (len = fis.read(buffer)) != -1) {
				System.out.println("---------------len:" + len);
				dos.write(buffer, 0, len);
				currentSize += len;
				updateHandler.sendMessage(updateHandler.obtainMessage(DO_ING));

			}
			if (canceled) {
				// 如果取消，不继续执行
				updateHandler.sendMessage(updateHandler
						.obtainMessage(DO_CANCEL));
				return;

			}
			// 写入文件end
			// 多个写入分割
			dos.write("\r\n".getBytes("UTF-8"));
			// 写入end
			dos.write(afterSb.toString().getBytes("UTF-8"));
			fis.close();
			dos.flush();
			if (httpURLConnection.getResponseCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								httpURLConnection.getInputStream()), 8192);// 8k
				StringBuilder sb = new StringBuilder();
				String line = null;
				try {
					while ((line = reader.readLine()) != null) {

						sb.append(line + "\n");
					}
					result = sb.toString().trim();
				} catch (IOException e) {
					e.printStackTrace();
				}

			} else {
				updateHandler.sendMessage(updateHandler.obtainMessage(DO_ERR,
						"上传失败," + httpURLConnection.getResponseCode()));
			}

		} catch (Exception e) {
			updateHandler.sendMessage(updateHandler.obtainMessage(DO_ERR,
					"上传失败," + e.getMessage()));

		} finally {
			try {
				if (httpURLConnection != null) {
					httpURLConnection.disconnect();
				}
				if (fis != null) {
					fis.close();
				}
				if (dos != null) {
					dos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		updateHandler.sendMessage(updateHandler.obtainMessage(DO_COMPLETE,
				result));

	}

}